package com.zhixue.content.service.impl;

import com.zhixue.content.mapper.CourseCategoryMapper;
import com.zhixue.content.model.dto.CourseCategoryTreeDto;
import com.zhixue.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Dragon
 * @description CourseCategoryServiceImpl
 * @date 2023/9/19 21:41
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        //将list转map,以备使用,排除根节点
//        Map<String, CourseCategoryTreeDto> mapTemp = courseCategoryTreeDtos
//                .stream()
//                .filter(item->!id.equals(item.getId()))
//                .collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
        HashMap<String, CourseCategoryTreeDto> mapTemp = new HashMap<>();
        //最终返回的list
        List<CourseCategoryTreeDto> categoryTreeDtos = new ArrayList<>();
        //依次遍历每个元素,排除根节点
        courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).forEach(item->{
            if(item.getParentid().equals(id)){
                mapTemp.put(item.getId(), item);
                categoryTreeDtos.add(item);
            }
            //找到当前节点的父节点
            CourseCategoryTreeDto courseCategoryTreeDto = mapTemp.get(item.getParentid());
            if(courseCategoryTreeDto!=null){
                //如果该父节点的ChildrenTreeNodes 属性为空，要new一个集合，得向该集合中存放它的子节点
                if(courseCategoryTreeDto.getChildrenTreeNodes() ==null){
                    courseCategoryTreeDto.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                //下边开始往ChildrenTreeNodes属性中放子节点
                courseCategoryTreeDto.getChildrenTreeNodes().add(item);
            }
        });
        return categoryTreeDtos;
    }
}
